// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'
import store from './store/store'
import Axios from 'axios'
import {
  Button,
  Tabbar,
  TabbarItem,
  NavBar,
  NoticeBar,
  Panel,
  Row,
  Col,
  Field,
  Cell,
  CellGroup,
  Checkbox,
  CheckboxGroup,
  Card,
  SubmitBar
} from 'vant'

Vue.use(Tabbar).use(TabbarItem).use(NavBar).use(Button).use(NoticeBar)
  .use(Panel).use(Row).use(Col).use(Field).use(Cell).use(CellGroup)
  .use(Checkbox).use(CheckboxGroup).use(Card).use(SubmitBar)

Vue.config.productionTip = false
// 定义全局默认配置
Axios.defaults.headers.common['Authentication-Token'] = store.state.token
// 页面刷新时，重新赋值token
if (sessionStorage.getItem('token')) {
  store.commit('set_token', sessionStorage.getItem('token'))
}

router.beforeEach((to, from, next) => {
  if (to.matched.some(r => r.meta.requireAuth)) {
    if (store.state.token) {
      next()
    } else {
      next({
        path: '/user'
      })
    }
  } else {
    next()
  }
})
// 添加请求拦截器
Axios.interceptors.request.use(config => {
// 在发送请求之前做些什么
// 判断是否存在token，如果存在将每个页面header都添加token
  if (store.state.token) {
    config.headers.common['Authentication-Token'] = store.state.token
  }
  return config
}, error => {
// 对请求错误做些什么
  return Promise.reject(error)
})

// http response 拦截器
Axios.interceptors.response.use(
  response => {
    return response
  }, error => {
    if (error.response) {
      switch (error.response.status) {
        case 401:
          this.$store.commit('del_token')
          router.replace({
            path: '/user'
          })
      }
    }
    return Promise.reject(error.response.data)
  })
/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  components: {App},
  template: '<App/>'
})
